<?php

namespace App\Jobs\System;
// 加载采集环境

use App\Models\Bureau\WxClubTeam;
use App\Models\Shop\WxShopGoods;
use App\Models\Shop\WxShopGoodsProduct;
use App\Models\Shop\WxShopOrder;
use App\Models\Shop\WxShopOrderGoods;
use App\Models\Used\WxUsedGood;
use App\Models\WxRefund;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Yansongda\Pay\Pay;

class AlipayTradeRefundQueryJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $out_trade_no;
    protected $out_refund_no;
    protected $try_rest;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($out_trade_no, $out_refund_no, $try_rest)
    {
        $this->out_trade_no = $out_trade_no;
        $this->out_refund_no = $out_refund_no;
        $this->try_rest = $try_rest;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $order_good = WxShopOrderGoods::where('refund_no', $this->out_refund_no)->first();
        if($order_good->state == 3){
            // 已退款
            return;
        }
        $shop_order = WxShopOrder::where('id', $order_good->order_id)->first();

        $flag = false;
        DB::beginTransaction();
        try {
            // todo:
            if($this->try_rest <= 0){
                $updated_at = Carbon::now();
                WxShopOrderGoods::where('id', $order_good->id)->update([
                    'state' => 3,
                    'updated_at' => $updated_at
                ]);
                $financial_type = 3;
                if($order_good->goods_type == 7){
                    $financial_type = 29;
                }
                if($shop_order->serial_number){
                    UserUtils::update_user_financial($order_good->buyer_user_id,$financial_type, $order_good->recharge,
                        '您收到了一笔来自「' . $order_good->name . '(规格：' . $order_good->product . ')」×' . $order_good->quantity . '件的退款，退款金额¥' . $order_good->recharge
                    );
                }
                $flag = true;
            }


            if(!$flag){
                $config = json_decode(Cache::get('app_pay_config'), true);
                if(_empty_($config)){
                    CheckBatchCahceDataLossJob::dispatch();
                }
                $outTradeNoPre = Utils::outTradeNoPre($this->out_trade_no, 'ali_shoporder_');
                $config['alipay']['default']['return_url'] = route('pay.return', ['out_trade_no'=>$outTradeNoPre]);
                $config['alipay']['default']['notify_url'] = env('APP_URL'). '/api/v1/app/ali/notify/app';

                $actionMap = [
                    'mini' => 'refund_mini',
                    'app' => 'refund_app',
                    'h5' => 'refund_h5',
                    'pos' => 'refund_pos',
                    'code' => 'refund_scan',
                    'code_pc' => 'refund_scan'
                ];

                $order = [
                    'out_trade_no' => $this->out_trade_no,
                    'out_request_no' => $this->out_refund_no,
                    '_action' => _array_key($actionMap, _empty_default_($shop_order->serial_platform_type, 'app'), 'refund_app'), // 默认值，查询退款网页订单
                ];
                $result = Pay::alipay()->query($order);
                if($result && $result->alipay_trade_fastpay_refund_query_response){
                    $result = $result->alipay_trade_fastpay_refund_query_response;
                    // 代表请求成功
                    if($result['code'] == 10000 || $result['msg'] == 'Success'){
                        if(_array_key($result, 'refund_status', '') == 'REFUND_SUCCESS'){
                            $nr = '您购买的：「' . $order_good->name . '(规格：' . $order_good->product . ')」×' . $order_good->quantity . '件的退款申请已处理完毕';
                            // 退款记录
                            $refund_record = new WxRefund();
                            $refund_record->user_id = $order_good->seller_user_id;
                            $refund_record->order_good_id = $order_good->id;
                            $refund_record->order_id = $order_good->order_id;
                            $refund_record->goods_id = $order_good->goods_id;
                            $refund_record->product_id = $order_good->product_id;
                            $refund_record->amount = $order_good->recharge;
                            $refund_record->goods_type = $order_good->goods_type;
                            $refund_record->save();

                            $refund_amount = $order_good['recharge'];
                            if(_array_key($result, 'refund_amount', 0) > 0){
                                $refund_amount = $result['refund_amount'];
                            }

                            WxShopOrderGoods::where('id', $order_good->id)->update([
                                'refund_no' => $this->out_refund_no,
                                'state' => 3,
                                'refund_from' => 1,
                                'refund_amount' => $refund_amount,
                                'refund_time' => _array_key($result, 'gmt_refund_pay', current_time()),
                                'refund_account' => ''
                            ]);
                            UserUtils::add_user_notice(6002, $order_good->seller_user_id, '商品退款通知', $nr, 100);
                            $flag = true;
                        }else if(in_array(_array_key($result, 'refund_status', ''), ['TRADE_CLOSED', 'REFUND_CLOSED', 'REFUND_ABNORMAL', 'TRADE_ABNORMAL'])){
                            $updated_at = Carbon::now();
                            WxShopOrderGoods::where('id', $order_good->id)->update([
                                'state' => 3,
                                'updated_at' => $updated_at
                            ]);
                            $financial_type = 3;
                            if($order_good->goods_type == 7){
                                $financial_type = 29;
                            }
                            if($shop_order->serial_number){
                                UserUtils::update_user_financial($order_good->buyer_user_id,$financial_type, $order_good->recharge,
                                    '您收到了一笔来自「' . $order_good->name . '(规格：' . $order_good->product . ')」×' . $order_good->quantity . '件的退款，退款金额¥' . $order_good->recharge
                                );
                            }
                            $flag = true;
                        }else{
                            throw new \Exception('重新尝试支付宝的退款查询refund_no：'.$this->out_refund_no);
                        }
                    }
                }
            }

            if($flag){
                UserUtils::add_user_notice(6002, $order_good->buyer_user_id, '商品退款通知', $nr, 100);

                $result_ = DB::table('wx_shop_order_goods as wg')
                    ->select(DB::raw('COUNT(*) as total_count, SUM(CASE WHEN state = 3 THEN 1 ELSE 0 END) as state_3_count'))
                    ->where('wg.order_id', $order_good->id)
                    ->first();

                if ($result_->total_count == $result_->state_3_count) {
                    WxShopOrder::where('id', $order_good->order_id)->update([
                        'pay_status' => 3,
                        'status' => 4,
                        'updated_at' => $updated_at
                    ]);
                }

                if(in_array($order_good->goods_type, FieldUtils::getShopGoodTypes())){
                    WxShopGoods::where('id', $order_good->goods_id)->decrement('buys', (int)($order_good->quantity));
                    WxShopGoodsProduct::where('id', $order_good->product_id)->increment('stock', (int)($order_good->quantity));
                }else{
                    if($order_good->goods_type == 6){
                        WxUsedGood::where('id', $order_good->goods_id)->update([
                            'status' => 6
                        ]);
                    }else if($order_good->goods_type == 7){
                        $team = WxClubTeam::find($order_good->product_id);
                        if ($team) {
                            $members_arr = $team->members; // 获取当前成员数组
                            if($members_arr){
                                $key = array_search((int)$order_good->buyer_user_id, $members_arr);
                                if ($key !== false) {
                                    unset($members_arr[$key]);
                                    // 设置并保存成员数组，确保触发属性修改器和事件
                                    $members = array_unique($members_arr);
                                    $team->members = $members;
                                    $team->members_num = count($members);
                                    $team->save();
                                    Cache::forget('get_join_info:'.$team->bureau_id.':'.$order_good->buyer_user_id);
                                    Cache::forget('bureau:avatars:'.$team->bureau_id);
                                }
                            }
                        }
                    }
                }
                DB::commit();
                return;
            }else{
                DB::rollBack();
                AlipayTradeRefundQueryJob::dispatch($this->out_trade_no, $this->out_refund_no, $this->try_rest - 1)->delay(now()->addSeconds(10));
            }
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            AlipayTradeRefundQueryJob::dispatch($this->out_trade_no, $this->out_refund_no, $this->try_rest - 1)->delay(now()->addSeconds(10));
            return;
        }

    }
}
